//
//  YXYComposeController.swift
//  SinaWeibo
//
//  Created by 袁向阳 on 16/7/3.
//  Copyright © 2016年 YXY.cn. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class YXYComposeController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setUpNav()
        setUpUI()
    }

    // MARK: - 设置导航栏
    private func setUpNav () {
        view.backgroundColor = UIColor.whiteColor()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "clickCancelBtn")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendWeibo")
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleView
    }
    
    // MARK: - 点击取消按钮
    @objc private func clickCancelBtn () {
        textView.resignFirstResponder()
        SVProgressHUD.dismiss()
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    // MARK: - 发送微博按钮
    @objc private func sendWeibo () {
        
        pictureView.userInteractionEnabled = false
        
        let status = textView.text
        // 发布微博
        if pictureView.imagesArray.count > 0 {
            // 图文微博
            let image = pictureView.imagesArray.first!
            let pic = UIImageJPEGRepresentation(image, 0.7)!
            upload(status, pic: pic)
            
        }else {
            // 文字微博
            update(status)
        }
        
    }
    
    // MARK: - 添加子控件
    private func setUpUI () {
        // 在 iOS7 之后，系统检测出控制器有导航栏，textView的文字自动下移
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.leading.trailing.equalTo(view)
            make.height.equalTo(44)
        }
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            make.leading.equalTo(textView).offset(10)
            make.width.height.equalTo(kWidth - 20)
        }
        toolBar.closure = { [weak self] (type: ComposeToolBarType) -> () in
            switch type {
            case .Picture:
                self?.selectImage()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                print("表情")
            case .Add:
                print("+")
            }
        }
        
        pictureView.closure = { [weak self] in
            self!.selectImage()
        }
        
        // MARK: - 监听键盘frame改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    // MARK: - 相册控制器
    lazy var pickerController: UIImagePickerController = {
        let p = UIImagePickerController()
        p.delegate = self
        return p
    }()
    // MARK: - 相册的点击事件
    private func selectImage () {
        
        presentViewController(pickerController, animated: true, completion: nil)
        
    }
    
    // MARK: - 键盘frame改变的方法
    @objc private func keyboardWillChangeFrame (noti: NSNotification) {
        let time = noti.userInfo! ["UIKeyboardAnimationDurationUserInfoKey"] as! NSTimeInterval
        let endFrame = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(-kHeight + endFrame.origin.y)
        }
        
        // 更新视图
        UIView.animateWithDuration(time) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    // MARK: - 设置titleView
    lazy var titleView: UILabel = {
        let lab = UILabel()
        let name = YXYUserAccountTool.sharedUserAccountTool.userAccount?.screen_name ?? ""
        let text = "发布微博\n\(name)"
        let textString = text as NSString
        let range = textString.rangeOfString("\(name)")
        let attr = NSMutableAttributedString(string: text)
        attr.addAttributes([NSForegroundColorAttributeName: themeColor,NSFontAttributeName: UIFont.systemFontOfSize(13)], range: range)
        let range2 = textString.rangeOfString("发布微博")
        attr.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(15)], range: range2)
        lab.attributedText = attr
        lab.numberOfLines = 0
        lab.textAlignment = .Center
        lab.sizeToFit()
        return lab
    }()
    
    // MARK: - textView
    lazy var textView: YXYCustomTextView = {
        let text = YXYCustomTextView()
        text.backgroundColor = UIColor.whiteColor()
        // 设置可以滚动
        text.alwaysBounceVertical = true
        // 设置拖拽键盘消失
        //text.keyboardDismissMode = .OnDrag
        text.delegate = self
        text.placeHolder = "分享新鲜事儿...分享新鲜事儿...分享新鲜事儿...分享新鲜事儿...分享新鲜事儿...分享新鲜事儿...分享新鲜事儿...分享新鲜事儿...分享新鲜事儿...分享新鲜事儿...分享新鲜事儿..."
        text.font = UIFont.systemFontOfSize(14)
        return text
    }()
    
    // MARK: - 底部toolBar
    lazy var toolBar: YXYComposeToolBar = YXYComposeToolBar()
    // MARK: - 图片视图
    lazy var pictureView: YXYComposePicture = YXYComposePicture()
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
// textView的代理方法
extension YXYComposeController :UITextViewDelegate {
    func scrollViewDidScroll(scrollView: UIScrollView) {
        textView.resignFirstResponder()
    }
    
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}

extension YXYComposeController :UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        // 对图片进行压缩
        //let smallImage = UIImage(data: UIImagePNGRepresentation(image)!, scale: 0.2)!
        //imageData?.writeToFile("/Users/yuanxiangyang/Desktop/test.jpg", atomically: true)
        
        let smallImage = scaleImageWithWidth(500, image: image)
        pictureView.addImage(smallImage)
        pickerController.dismissViewControllerAnimated(false, completion: nil)
    }
}

// MARK: - 压缩图片
extension YXYComposeController {
    private func scaleImageWithWidth (width: CGFloat, image: UIImage) -> UIImage {
        
        // 比如压缩前 宽 2000  高 3000
        // 那么压缩后 宽 600   高 900
        // 交叉相乘相等..
        
        let height = (image.size.height * width) / image.size.width
        // 开启图片上下文
        UIGraphicsBeginImageContext(CGSize(width: width, height: height))
        // 将图片绘制到上下文中
        image.drawInRect(CGRect(x: 0, y: 0, width: width, height: height))
        // 从上下文获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        // 关闭上下文
        UIGraphicsEndImageContext()
        
        return image
    }
}

// MARK: - 发布微博
extension YXYComposeController {
    private func update (status: String) {
        YXYNetWorkTool.sharedWorkTool.updateTextWeibo(status, success: { (response) -> () in
            
            self.dismissViewControllerAnimated(true, completion: nil)
            
            }) { (error) -> () in
                
                print(error.debugDescription)
                
        }
        pictureView.userInteractionEnabled = false
    }
    
    private func upload (status: String, pic: NSData) {
        
        YXYNetWorkTool.sharedWorkTool.uploadWeibo(status, pic: pic, success: { (response) -> () in
            
            self.dismissViewControllerAnimated(true, completion: nil)
            print("成功")
            
            }) { (error) -> () in
                
                print(error?.debugDescription)
                
        }
    }
}

